import { customRef } from 'vue'

//实现防抖功能函数
export function useDebouncedRef(value: unknown, delay = 200) {
    let timeout: ReturnType<typeof setTimeout> //timeout的类型应该是ReturnType<typeof setTimeout>，而不是简单的number类型
    return customRef((track, trigger) => {
        return {
            get() {
                track()
                return value
            },
            set(newValue) {
                clearTimeout(timeout)
                timeout = setTimeout(() => {
                    value = newValue
                    trigger()
                }, delay)
            }
        }
    })
}

//格式化输入值：创建一个ref，靠用户输入自动转为大写
export function useUpperCaseRef(initiaValue: string) {
    return customRef((track, trigger) => {
        let value = initiaValue;
        return {
            get() {
                track();
                return value;
            },
            set(newValue) {
                //转换为大写
                value = newValue.toUpperCase();
                trigger();
            }
        }
    })
}


//延迟一定时间更新值，用于节约性能消耗
export function unseDelayedRef(initiaValue: string, delay: number) {
    return customRef((track, trigger) => {
        let value = initiaValue;
        return {
            get() {
                track();
                return value;
            },
            set(newValue) {
                setTimeout(() => {
                    value = newValue;
                    trigger();
                }, delay)
            }
        }
    })
}

// 获取当前日期和时间的格式化字符串
export function getFormattedCurrentDateTime(): string {
    const now = new Date();
    const year = now.getFullYear();
    const month = padZero(now.getMonth() + 1);
    const day = padZero(now.getDate());
    const hours = padZero(now.getHours());
    const minutes = padZero(now.getMinutes());
    const seconds = padZero(now.getSeconds());
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function padZero(num: number): string {
    return num < 10 ? `0${num}` : num.toString();
}

// 验证邮箱格式
export function validateEmail(email: string): boolean {
    const reg =
        /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@(([^<>()[\]\\.,;:\s@"]+\.)+[^<>()[\]\\.,;:\s@"]{2,})$/i;
    return reg.test(email);
}

// 验证手机号格式
export function validatePhone(phone: string): boolean {
    const reg = /^(?:(?:\+|00)86)?1\d{10}$/;
    return reg.test(phone);
}